package com.bmmtwabp.employeedashbord.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.RemoteEndpoint.Async;
import javax.websocket.Session;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: websocket工具类
 * @Param:
 * @return:
 * @Author: fenghouzhi
 * @Date: 5:08 PM 2018/10/22
 */
@Slf4j
public class WebSocketUtil {

  /**
   * 使用ConcurrentHashMap维护在线的用户session会话
   */
  private static final Map<String, Session> ONLINE_SESSION = new ConcurrentHashMap<>();

  /**
   * 存入session,存入用户
   */
  public static void addSession(String openId, Session session) {
    if (!ONLINE_SESSION.containsKey(openId)) {
      ONLINE_SESSION.put(openId, session);
    } else {
      ONLINE_SESSION.putIfAbsent(openId, session);
    }
  }

  /**
   * 删除session
   */
  public static void removeSession(String openId) {
    ONLINE_SESSION.remove(openId);
  }

  /**
   * 向某个用户发送消息
   *
   * @param session 某一用户的session对象
   */
  public static void sendMessage(Session session, String message) {
    if (session == null) {
      return;
    }
    Async async = session.getAsyncRemote();
    async.sendText(message);
  }

  /**
   * 向所有在线用户发送消息
   */
  public static void sendMessageForAll(String message) {
    ONLINE_SESSION.forEach((sessionId, session) -> sendMessage(session, message));
  }

  /**
   * 服务端主动推送消息
   */
  public static void serverToClientMsg(String openId, String message) {
    if (null != openId && !"".equals(openId)) {
      Session session = ONLINE_SESSION.get(openId);
      if (session == null) {
        return;
      }
      sendMessage(session, message);
      log.info("服务端推送给用户[ " + openId + "  ]消息success!");
    } else {
      sendMessageForAll(message);
    }
  }

}
